﻿using MAIModel.Commands;
using MAIModel.Views;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace MAIModel.ViewModels
{
    /// <summary>
    /// 0、Current class:
    /// 1、Realize ：
    /// 2、Current scheme：
    /// 3、Why it is better than other schemes：
    /// 4、Technical standard / dependency：
    /// 5、Reference：
    /// </summary>
    public class MainViewModel : INotifyPropertyChanged
    {
        #region Field | Property | Collection | Command

        #region Field
        private object _currentView;                //The current view object.
        private string _currentTime;                //The current time.
        private string _currentModel;               //The current model name.
        private DispatcherTimer _timer;             //Time label timer.
        private ShareOllamaObject _ollamaObject;    //OllamaAPI object.
        #endregion

        #region Property
        public object CurrentView
        {
            get => _currentView;
            set
            {
                _currentView = value;
                OnPropertyChanged();
            }
        }
        public string CurrentTime
        {
            get => _currentTime;
            set
            {
                _currentTime = value;
                OnPropertyChanged();
            }
        }
        public string CurrentModel
        {
            get => _currentModel;
            set
            {
                _currentModel = value;
                OnPropertyChanged();
            }
        }
        #endregion

        #region Collection
        private ObservableCollection<UserControl> _viewList;    //视图列表
        private ObservableCollection<UserControl> ViewList
        {
            get => _viewList;
            set
            {
                _viewList = value;
                OnPropertyChanged();
            }
        }
        #endregion

        #region Command
        public ICommand SwitchToViewCommand { get; }
        public ICommand ClosingWindowCommand { get; }

        #endregion

        #endregion

        #region Constructor
        public MainViewModel()
        {
            //Initialize Ollama object.  
            _ollamaObject = new ShareOllamaObject(); 

            //bind command method
            SwitchToViewCommand = new ObjectPassingCommand(OnSwitchToView);
            ClosingWindowCommand = new EventsCommand<CancelEventArgs>(OnClosingWindow);

            //create view
            _viewList = new ObservableCollection<UserControl>();
            ViewList.Add(new SettingView(_ollamaObject));
            ViewList.Add(new ChatMdView(_ollamaObject));

            //Set the default display of subview 1.
            CurrentModel = _ollamaObject.Ollama.SelectedModel;
            InitializeTimer();
            CurrentView = ViewList[0];
        }

        #region The window close event 
        /// <summary>
        ///trigger close event
        /// </summary>
        private void OnClosingWindow(CancelEventArgs e)
        {
            if (MessageBox.Show("确定要关闭程序吗？", "确认关闭", MessageBoxButton.YesNo) == MessageBoxResult.No)
                e.Cancel = true;
            else  ClearingResources();
        }
        /// <summary>
        /// Clear the resource.
        /// </summary>
        private void ClearingResources()
        {
            ShareOllamaObject.CloseProcess("ollama_llama_server");
            Debug.Print($"{ShareOllamaObject.GetProgramName()}:关闭成功...");
        }
        #endregion
        #endregion

        #region Other mothod
        //Initialize time label timer //Each one second update once
        private void InitializeTimer()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1); 
            _timer.Tick += Timer_Tick;
            _timer.Start();
        }
        //update current time
        private void Timer_Tick(object sender, EventArgs e)
        {
            CurrentTime = DateTime.Now.ToString("HH:mm:ss");
            CurrentModel = _ollamaObject.Ollama.SelectedModel;
        }

        #endregion

        #region Command method

        #region View switch
        //set the view
        public void OnSwitchToView(object operationItem)
        {
            var viewObj = ViewList.FirstOrDefault(viewObj => viewObj.GetType().Name.Equals(operationItem));
            if (viewObj == null)
            {
                var newViewObj =new UserControl();
                switch (operationItem)
                {
                    case "ChatMdView":
                        newViewObj = new ChatMdView(_ollamaObject);
                        break;
                    case "SettingView":
                        newViewObj = new SettingView(_ollamaObject);
                        break;
                    default:
                        break;
                }
                ViewList.Add(newViewObj);
                CurrentView = newViewObj;
            }
            else
            {
                CurrentView = viewObj;
            }
        }
        #endregion

        #endregion

        #region Property changed event
        public event PropertyChangedEventHandler? PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}
